﻿using Microsoft.Extensions.Hosting;
using Quartz;
using System.Threading.Tasks;
using System.Threading;
using Quartz.Impl;

namespace AuthorityManagement.Quartz
{
    public class QuartzHostedService : IHostedService
    {
        private readonly IScheduler _scheduler;

        public QuartzHostedService(IScheduler scheduler)
        {
            _scheduler = scheduler;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // 创建作业和触发器  
            IJobDetail job = JobBuilder.Create<TestJob>()
                .WithIdentity("myJob", "group1")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("myTrigger", "group1")
                .WithCronSchedule("0/3 * * * * ?") // 每3秒执行一次  
                .Build();

            // 将作业和触发器加入调度器  
            await _scheduler.ScheduleJob(job, trigger);

            // 启动调度器  
            await _scheduler.Start(cancellationToken);
        }


        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _scheduler.Shutdown(cancellationToken);
        }
    }

}
